package com.moorror.codegenvel.common.dialog;

import com.intellij.openapi.project.Project;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.ListTableModel;
import com.moorror.codegenvel.common.table.TableAddNewRowAction;
import com.moorror.codegenvel.common.table.TreeLineObject;
import com.moorror.codegenvel.common.table.TreeLineWrap;
import com.moorror.codegenvel.utils.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

import javax.swing.*;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @Author jiyanghuang
 * @Date 2022/8/28 00:32
 */
public class DialogFormTable implements DialogFormMark {

    private Project project;

    private ToolbarDecorator decorator;

    private JBTable tableView;

    private JPanel tablePanel;

    private Consumer<List<? extends TreeLineObject>> doUpdate;

    private String dialogTitle;

    /**
     *
     * @param project
     * @param dialogTitle
     * @param clazz 一行由哪个类来描述
     * @param tableData 数据List
     * @param doUpdate 关闭时，重新更新整个List
     */
    public DialogFormTable(Project project, String dialogTitle, Class<? extends TreeLineObject> clazz, List<? extends TreeLineObject> tableData, Consumer<List<? extends TreeLineObject>> doUpdate) {
        this.project = project;
        this.dialogTitle = dialogTitle;
        tableView = TreeLineWrap.tableView(clazz, tableData, project);
        ListTableModel listTableModel = (ListTableModel) tableView.getModel();
        decorator = ToolbarDecorator.createDecorator(tableView);
        TableAddNewRowAction addLineAction = new TableAddNewRowAction(clazz, listTableModel);
        decorator.setAddAction(addLineAction);
        tablePanel = decorator.createPanel();
        this.doUpdate = doUpdate;
    }

    @Override
    public JComponent jComponent() {
        return tablePanel;
    }

    @Override
    public String title() {
        if (StringUtils.isBlank(dialogTitle)) {
            return "Editor Table";
        }
        return dialogTitle;
    }

    @Override
    public Function<DialogFormTable, Pair<Boolean, String>> okFun() {
        return (form) -> {
//            doUpdate.accept(form.fetchText());
            if(null != tableView){
                ListTableModel listTableModel = (ListTableModel)tableView.getModel();
                List values = TreeLineWrap.lastValue((listTableModel.getItems()));
                if(null != doUpdate){
                    doUpdate.accept(values);
                }
                System.out.println("----------------->");
                System.out.println(JacksonUtils.toJSONString(values));
            }
            return Pair.of(true, null);
        };
    }
}
